<template>
  <div class="product-cascader">
    <Row :gutter="gutter">
      <Col :span="computedSpans.brandSpan">
        <FormItem 
          v-if="showFormItem"
          :label="brandLabel"
          :name="brandName"
          :rules="brandRequired ? [{ required: true, message: `请选择${brandLabel}` }] : undefined"
        >
          <Select
            v-model:value="innerBrandId"
            :placeholder="brandPlaceholder"
            :options="brandOptions"
            :loading="brandLoading"
            :disabled="disabled"
            show-search
            :filter-option="filterOption"
            @change="onBrandChange"
            :getPopupContainer="getPopupContainer"
            allowClear
          />
        </FormItem>
        <Select
          v-else
          v-model:value="innerBrandId"
          :placeholder="brandPlaceholder"
          :options="brandOptions"
          :loading="brandLoading"
          :disabled="disabled"
          show-search
          :filter-option="filterOption"
          @change="onBrandChange"
          :getPopupContainer="getPopupContainer"
          allowClear
        />
      </Col>
      
      <Col :span="computedSpans.spuSpan">
        <FormItem 
          v-if="showFormItem"
          :label="spuLabel"
          :name="spuName"
          :rules="spuRequired ? [{ required: true, message: `请选择${spuLabel}` }] : undefined"
        >
          <Select
            v-model:value="innerSpuId"
            :placeholder="spuPlaceholder"
            :options="spuOptions"
            :loading="spuLoading"
            :disabled="disabled || !innerBrandId"
            show-search
            :filter-option="filterOption"
            @change="onSpuChange"
            :getPopupContainer="getPopupContainer"
            allowClear
          />
        </FormItem>
        <Select
          v-else
          v-model:value="innerSpuId"
          :placeholder="spuPlaceholder"
          :options="spuOptions"
          :loading="spuLoading"
          :disabled="disabled || !innerBrandId"
          show-search
          :filter-option="filterOption"
          @change="onSpuChange"
          :getPopupContainer="getPopupContainer"
          allowClear
        />
      </Col>
      
      <Col :span="computedSpans.skuSpan" v-if="showSku">
        <FormItem 
          v-if="showFormItem"
          :label="skuLabel"
          :name="skuName"
          :rules="skuRequired ? [{ required: true, message: `请选择${skuLabel}` }] : undefined"
        >
          <Select
            v-model:value="innerSkuId"
            :placeholder="skuPlaceholder"
            :options="skuOptions"
            :loading="skuLoading"
            :disabled="disabled || !innerSpuId"
            show-search
            :filter-option="filterOption"
            @change="onSkuChange"
            :getPopupContainer="getPopupContainer"
            allowClear
          />
        </FormItem>
        <Select
          v-else
          v-model:value="innerSkuId"
          :placeholder="skuPlaceholder"
          :options="skuOptions"
          :loading="skuLoading"
          :disabled="disabled || !innerSpuId"
          show-search
          :filter-option="filterOption"
          @change="onSkuChange"
          :getPopupContainer="getPopupContainer"
          allowClear
        />
      </Col>
    </Row>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, computed, onMounted } from 'vue';
import { Row, Col, FormItem, Select } from 'ant-design-vue';
import { getPopupContainer } from '@vben/utils';
import { brandList } from '#/api/trade/brand';
import { spuList } from '#/api/trade/spu';
import { skuList } from '#/api/trade/sku';
import type { DefaultOptionType } from 'ant-design-vue/es/select';

interface Props {
  // 双向绑定的值
  brandId?: string | number;
  spuId?: string | number;
  skuId?: string | number;
  
  // 是否禁用
  disabled?: boolean;
  
  // 是否显示SKU选择
  showSku?: boolean;
  
  // 是否显示FormItem包装
  showFormItem?: boolean;
  
  // 栅格布局
  gutter?: number;
  brandSpan?: number;
  spuSpan?: number;
  skuSpan?: number;
  
  // 标签文本
  brandLabel?: string;
  spuLabel?: string;
  skuLabel?: string;
  
  // 占位符文本
  brandPlaceholder?: string;
  spuPlaceholder?: string;
  skuPlaceholder?: string;
  
  // 表单字段名
  brandName?: string | string[];
  spuName?: string | string[];
  skuName?: string | string[];
  
  // 是否必填
  brandRequired?: boolean;
  spuRequired?: boolean;
  skuRequired?: boolean;
}

interface Emits {
  (e: 'update:brandId', value: string | number | undefined): void;
  (e: 'update:spuId', value: string | number | undefined): void;
  (e: 'update:skuId', value: string | number | undefined): void;
  (e: 'change', value: {
    brandId?: string | number;
    spuId?: string | number;
    skuId?: string | number;
  }): void;
}

const props = withDefaults(defineProps<Props>(), {
  disabled: false,
  showSku: true,
  showFormItem: true,
  gutter: 16,
  brandSpan: 8,
  spuSpan: 8,
  skuSpan: 8,
  brandLabel: '品牌',
  spuLabel: 'SPU',
  skuLabel: 'SKU',
  brandPlaceholder: '请选择品牌',
  spuPlaceholder: '请先选择品牌',
  skuPlaceholder: '请先选择SPU',
  brandRequired: false,
  spuRequired: false,
  skuRequired: false
});

const emit = defineEmits<Emits>();

// 内部状态
const innerBrandId = ref<string | number | undefined>(props.brandId);
const innerSpuId = ref<string | number | undefined>(props.spuId);
const innerSkuId = ref<string | number | undefined>(props.skuId);

// 选项数据
const brandOptions = ref<DefaultOptionType[]>([]);
const spuOptions = ref<DefaultOptionType[]>([]);
const skuOptions = ref<DefaultOptionType[]>([]);

// 加载状态
const brandLoading = ref(false);
const spuLoading = ref(false);
const skuLoading = ref(false);

// 计算属性：调整栅格布局
const computedSpans = computed(() => {
  if (!props.showSku) {
    return {
      brandSpan: 12,
      spuSpan: 12,
      skuSpan: 0
    };
  }
  return {
    brandSpan: props.brandSpan,
    spuSpan: props.spuSpan,
    skuSpan: props.skuSpan
  };
});

// 监听外部props变化
watch(() => props.brandId, (newValue) => {
  if (newValue !== innerBrandId.value) {
    innerBrandId.value = newValue;
  }
});

watch(() => props.spuId, (newValue) => {
  if (newValue !== innerSpuId.value) {
    innerSpuId.value = newValue;
  }
});

watch(() => props.skuId, (newValue) => {
  if (newValue !== innerSkuId.value) {
    innerSkuId.value = newValue;
  }
});

// 监听内部值变化，同步到外部
watch(innerBrandId, (newValue) => {
  emit('update:brandId', newValue);
  emitChange();
});

watch(innerSpuId, (newValue) => {
  emit('update:spuId', newValue);
  emitChange();
});

watch(innerSkuId, (newValue) => {
  emit('update:skuId', newValue);
  emitChange();
});

// 发出change事件
const emitChange = () => {
  emit('change', {
    brandId: innerBrandId.value,
    spuId: innerSpuId.value,
    skuId: innerSkuId.value
  });
};

// 过滤选项
const filterOption = (input: string, option: any) => {
  return option.label.toLowerCase().includes(input.toLowerCase());
};

// 加载品牌列表
const loadBrandOptions = async () => {
  brandLoading.value = true;
  try {
    const { rows } = await brandList({
      pageNum: 1,
      pageSize: 200
    });
    brandOptions.value = rows.map(item => ({
      label: item.brandName,
      value: item.id
    }));
  } finally {
    brandLoading.value = false;
  }
};

// 加载SPU列表
const loadSpuOptions = async (brandId: string | number) => {
  spuLoading.value = true;
  try {
    const { rows } = await spuList({
      brandId,
      pageNum: 1,
      pageSize: 200
    });
    spuOptions.value = rows.map(item => ({
      label: item.spuName,
      value: item.id
    }));
  } finally {
    spuLoading.value = false;
  }
};

// 加载SKU列表
const loadSkuOptions = async (spuId: string | number) => {
  skuLoading.value = true;
  try {
    const { rows } = await skuList({
      spuId,
      pageNum: 1,
      pageSize: 200
    });
    skuOptions.value = rows.map(item => ({
      label: item.skuName,
      value: item.id
    }));
  } finally {
    skuLoading.value = false;
  }
};

// 品牌变化处理
const onBrandChange = async (value: string | number | undefined) => {
  // 清空下级选项
  innerSpuId.value = undefined;
  innerSkuId.value = undefined;
  spuOptions.value = [];
  skuOptions.value = [];
  
  if (value) {
    await loadSpuOptions(value);
  }
};

// SPU变化处理
const onSpuChange = async (value: string | number | undefined) => {
  // 清空下级选项
  innerSkuId.value = undefined;
  skuOptions.value = [];
  
  if (value && props.showSku) {
    await loadSkuOptions(value);
  }
};

// SKU变化处理
const onSkuChange = (value: string | number | undefined) => {
  // SKU是最后一级，无需处理下级
};

// 初始化数据加载
const initializeData = async () => {
  // 加载品牌列表
  await loadBrandOptions();
  
  // 如果有初始品牌ID，加载对应的SPU列表
  if (innerBrandId.value) {
    await loadSpuOptions(innerBrandId.value);
    
    // 如果有初始SPU ID，加载对应的SKU列表
    if (innerSpuId.value && props.showSku) {
      await loadSkuOptions(innerSpuId.value);
    }
  }
};

// 组件挂载时初始化
onMounted(() => {
  initializeData();
});

// 暴露方法供外部调用
defineExpose({
  loadBrandOptions,
  loadSpuOptions,
  loadSkuOptions,
  initializeData
});
</script>

<style scoped>
.product-cascader {
  /* width: 100%; */
}
:where(.css-dev-only-do-not-override-aza1th).ant-form-item {
  margin-bottom: 0;
}
.ant-form-item-label {
  font-weight: 500;;
}
</style>
